package com.whu.helpluojia.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//拦截带有RestController和Controller注解的类
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法，出现异常的时候，会跳转到这里，返回自定义的R类型结果，
     * @return
     */
    //异常处理注解：处理SQL异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        //判断当前SQL异常是否为重复存储（唯一约束）异常
        if(ex.getMessage().contains("Duplicate entry")){
            //把message按照空格分成数组，其中split[2]就是重复存储的名称信息
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 异常处理方法:处理用户自定义抛出的异常
     * @return
     */
    @ExceptionHandler(UserException.class)
    public R<String> exceptionHandler(UserException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

}
